//
//  CommentsListViewController.m
//  friendCyc
//
//  Created by sun on 13-4-1.
//  Copyright (c) 2013年 sun. All rights reserved.
//

#import "CommentsListViewController.h"
#import "StatusCell.h"
#import "CommentsCell.h"
#import "WriteStatusViewController.h"
#import "EGOPhotoGlobal.h"
#import "MyPhotoSource.h"
#import "MyPhoto.h"
#import "FirCirLocalResourceDataSource.h"
#import "FirCirCommentInfo.h"
#import "FirCirCommentDataSource.h"
#import "FirendCircleDataSource.h"

@interface CommentsListViewController ()

@end

@implementation CommentsListViewController

@synthesize status;

-(void)initUI
{
    self.view.backgroundColor = VIEW_BG_COLOR;
    
    [self createTitle];
    self.mtitle.text = @"所有评论";
    
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回" target:self action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem *nextItem = [self createBarButtonItemWithTitle:@"发表评论"
                                                            target:self
                                                            action:@selector(writeNewComments:)];
    self.navItem.rightBarButtonItem = nextItem;
    
    statusTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, [self getStatusHeight]) style:UITableViewStylePlain];
    statusTable.dataSource = self;
    statusTable.delegate = self;
    
    commentsTable = [[UITableView alloc]initWithFrame:CGRectMake(0, TOPBAR_HIGHT, WINDOW_WIDTH, WINDOW_HIGTH - TOPBAR_HIGHT - 20) style:UITableViewStylePlain];
    commentsTable.dataSource = self;
    commentsTable.delegate = self;
    commentsTable.tableHeaderView = statusTable;
    [self.view addSubview:commentsTable];
}


- (void)writeNewComments:(id)sender
{
    [[DataControl shareControl].fccommentDS SetCommentSendInfo:status.mail
                                                     withNewID:status.statusId
                                                   withSpeakTo:status.mail];
    
    [[ViewManager sharedViewManager] showView:VI_COMMENT
                             withIsRemoveCurV:false
                                withDirection:VD_RIGHT];
}

-(void)backButtonPressed
{
    [[ViewManager sharedViewManager] backView:self];
}

- (void)imageButtonClicked:(int)btnTag
{
    NSMutableArray *photos = [[NSMutableArray alloc]init];
    for (int imgCnt = 0; imgCnt < [self.status.imageIDArray count]; imgCnt++) {
        NSString *picid = [self.status.imageIDArray objectAtIndex:imgCnt];
        NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picid];
        if (![imgUrl isEqualToString:@""]) {
            MyPhoto *photo = [[MyPhoto alloc] initWithImage:[UIImage imageWithContentsOfFile:imgUrl]];
            [photos addObject:photo];
        }
    }
    MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:photos];
    EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:photoController];
    
    navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}

-(void)ImageArrBtnClicked:(int)btnTag withImageTag:(int)imageTag
{
    
        NSMutableArray *photos = [[NSMutableArray alloc]init];
        for (int imgCnt = 0; imgCnt < [status.imageIDArray count]; imgCnt++) {
            NSString *picid = [status.imageIDArray objectAtIndex:imgCnt];
            NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picid];
            if (![imgUrl isEqualToString:@""]) {
                MyPhoto *photo = [[MyPhoto alloc] initWithImage:[UIImage imageWithContentsOfFile:imgUrl]];
                [photos addObject:photo];
            }
        }
        MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:photos];
        EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:photoController];
        
        navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        navController.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:navController animated:YES completion:nil];
    
    if (imageTag >= 0 && imageTag < status.imageIDArray.count) {
        [photoController moveToPhotoAtIndex:imageTag animated:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -private fun-
-(void)refreshView
{
    if (status != nil) {
        [status SortCommentArr];
    }
    
    [statusTable reloadData];
    [commentsTable reloadData];
}

-(void)viewWillShow
{
    [self refreshView];
}

-(void)PackUpCell
{
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:[DataControl shareControl].fircirDS.iPackupRow
                                              inSection:[DataControl shareControl].fircirDS.iPackupSection];
    [statusTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]
                       withRowAnimation:UITableViewRowAnimationNone];
    
    if ([DataControl shareControl].fircirDS.bPackup) {
        [statusTable scrollToRowAtIndexPath:indexPath
                           atScrollPosition:UITableViewScrollPositionNone
                                   animated:NO];
    }
    
    commentsTable.tableHeaderView = statusTable;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (tableView != statusTable) {
        if (status != nil) {
            return status.commentsCount;
        }
    }
        
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == statusTable) {
        CGFloat height = [self getStatusHeight];
        [statusTable setFrame:CGRectMake(0, 0, 320, height)];
        return  height;
    }else {
        return [self getTheCellHeight:indexPath.row];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == statusTable) {
        static NSString *CellIdentifier = @"StatusCell";
        StatusCell *cell = (StatusCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[StatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
            cell.statusContent.NumberOfLines = 0;
        }
        cell.status = self.status;
        cell.delegate = self;
        [cell reloadCell];
        
        return cell;
    }else {
        static NSString *CellIdentifier = @"CommentsCell";
        CommentsCell *cell = (CommentsCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[CommentsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0];
            cell.contentView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0];
            cell.commentsContent.NumberOfLines = 0;
        }
        
        if (status != nil && indexPath.row >= 0 && indexPath.row < [status.commentArr count]) {
            NSString *commentid = [status.commentArr objectAtIndex:indexPath.row];
            FirCirCommentInfo *comments = [[DataControl shareControl].fccommentDS getCommentInfoByID:commentid];
            if (comments != nil) {
                cell.comments = comments;
                [cell reloadCell];
            }
        }
        
        
        return cell;
    }
}

- (CGFloat)getTheCellHeight:(int)row
{
    CGFloat height = 250;
    CGFloat contentWidth = 280;
    
    if (status == nil) {
        return height;
    }
    
    // 设置字体
    UIFont *font = [UIFont fontWithName:@"Arial" size:14];
    
    NSString *commentid = @"";
    
    if (row >= 0 && row < status.commentArr.count) {
        commentid = [status.commentArr objectAtIndex:row];
    }
    
    FirCirCommentInfo *comments = [[DataControl shareControl].fccommentDS getCommentInfoByID:commentid];
    
    if (comments == nil) {
        return height;
    }
    
    // 显示的内容
    NSString *content = comments.content;
    // 计算出长宽
    CGSize size = [content sizeWithFont:font
                      constrainedToSize:CGSizeMake(contentWidth, CGFLOAT_MAX)
                          lineBreakMode:NSLineBreakByTruncatingTail];
    if (comments.stIndex == FCG_ONE_SOUND) {
        height = 220;
    }else if(comments.stIndex == FCG_ONE_TEXT)
    {
        height = size.height + 140;
    }
    // 返回需要的高度
    return height;
}

- (CGFloat)getStatusHeight
{
    CGFloat height = 280;
    CGFloat imagehigh = 0.0f;
    if (status != nil) {
        if (status.imageIDArray.count > 0) {
            
            if (status.imageIDArray.count == 1) {
                NSString *picsrl = [status.imageIDArray objectAtIndex:0];
                NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picsrl];
                
                if (![imgUrl isEqualToString:@""]) {
                    UIImage *image = [UIImage imageWithContentsOfFile:imgUrl];
                    CGFloat w = 1.0f;
                    CGFloat h = 1.0f;
                    if (image.size.width>280) {
                        w = image.size.width/280;
                    }
                    if (image.size.height>72) {
                        h = image.size.height/72;
                    }
                    CGFloat scole = w>h ? w:h;
                    
                    imagehigh = image.size.height/scole;
                }
            }
            else
            {
                
                int iimagerow = (status.imageIDArray.count - 1) / 3 + 1;
                imagehigh = (ARR_IMAGE_INTERVAL + ARR_IMAGE_WIDTH) * iimagerow - ARR_IMAGE_INTERVAL;
            }
            
        }
        
        if (status.stIndex == FCG_ONE_SOUND) {
            
            
            
            
            
            if (imagehigh > 0) {
                height = STATUSCELL_HEAD_HIGH +
                STATUSCELL_INTERVAL * 5 +
                STATUSCELL_SOUNDBTN_W +
                imagehigh +
                30 +
                32;
            }
            else
            {
                height = STATUSCELL_HEAD_HIGH +
                STATUSCELL_INTERVAL * 3 +
                STATUSCELL_SOUNDBTN_W +
                32;
            }
            
        }
        else
        {
            UIFont *font = [UIFont fontWithName:@"Arial" size:14];
            CGFloat contentWidth = 280;
            
            NSString *content = status.statusText;
            CGSize size = [content sizeWithFont:font
                              constrainedToSize:CGSizeMake(contentWidth, CGFLOAT_MAX)
                                  lineBreakMode:NSLineBreakByTruncatingTail];
            
            if (status.ipackuptype == PPT_NULL) {
                if (size.height > 120) {
                    size = [content sizeWithFont:font
                               constrainedToSize:CGSizeMake(contentWidth, 120)
                                   lineBreakMode:NSLineBreakByTruncatingTail];
                    
                    status.ipackuptype = PPT_SHOWMORE;
                }
                else
                {
                    status.ipackuptype = PPT_NULL;
                }
            }
            else if(status.ipackuptype == PPT_SHOWMORE)
            {
                size = [content sizeWithFont:font
                           constrainedToSize:CGSizeMake(contentWidth, 120)
                               lineBreakMode:NSLineBreakByTruncatingTail];
            }
            
            if (status.ipackuptype == PPT_NULL) {
                if (imagehigh > 0) {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 5 +
                    size.height +
                    imagehigh +
                    30 +
                    32;
                }
                else
                {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 3 +
                    size.height +
                    32;
                }
                
            }
            else
            {
                if (imagehigh > 0) {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 6 +
                    size.height +
                    32 +
                    imagehigh +
                    30 +
                    32;
                }
                else
                {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 4 +
                    size.height +
                    32 +
                    32;
                }
            }
        }
    }
    
    return height;
}

@end
